from time import sleep

import pytest
import yaml
from selenium import webdriver
from selenium.webdriver.common.by import By


class Test_Wework():

    def setup(self):
        # 复用浏览器，
        opt = webdriver.ChromeOptions()
        opt.debugger_address = "127.0.0.1:9222"
        self.driver = webdriver.Chrome(options=opt)
        # self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(5)

    def teardown(self):
        self.driver.quit()

    # 使用复用浏览器，可以实现避免扫描登录，也可以拿到cookie
    def testwework(self):
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # self.driver.find_element_by_id("menu_contacts").click()
        sleep(5)
        # print(self.driver.get_cookies())
        cookies = self.driver.get_cookies()
        with open("cookie.yml", "w", encoding="UTF-8") as f:
            yaml.dump(cookies, f)

    # 获取用户信息
    def get_user_data():
        with open("username.yml") as f:
            user = yaml.safe_load(f)
        return user

    # 打开新的浏览器，使用cookie进行登录
    @pytest.mark.parametrize(["U", "U2", "mail", "tel", "expect"], get_user_data())
    def testweixinwork(self, U, U2, mail, tel, expect):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get("https://work.weixin.qq.com/wework_admin/loginpage_wx")
        with open("cookie.yml") as f:
            cookies = yaml.safe_load(f)
            print(cookies)
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        sleep(5)
        self.driver.find_element_by_id("menu_contacts").click()
        self.driver.find_element_by_link_text("添加成员").click()
        sleep(3)

        self.driver.find_element_by_id("username").send_keys(U)
        self.driver.find_element_by_id("memberAdd_english_name").send_keys(U2)
        self.driver.find_element_by_id("memberAdd_acctid").send_keys(mail)
        self.driver.find_element_by_id("memberAdd_phone").send_keys(tel)
        sleep(2)
        self.driver.execute_script('document.documentElement.scrollTop=2000')
        sleep(2)
        self.driver.find_element_by_link_text("保存").click()
        sleep(8)

        elements = self.driver.find_elements_by_css_selector(".member_colRight_memberTable_td:nth-child(2)")


        print(elements)
        for x in elements:
            if x.get_attribute("tile") == "U":
                return True
